package utils

import (
	"fmt"
	"github.com/gomodule/redigo/redis"
	"time"
)
var(
	MaxIdle=5
	MaxActive=10
	MaxIdleTimeout=10*time.Second
	timeout=10*time.Second
)
var RedisClient *redis.Pool

func init2()  {
	RedisClient = GetRedisDBPool("127.0.0.1:6379","",0)
}
func GetRedisDBPool(addr, pwd string, db int) *redis.Pool {
	return &redis.Pool{
		MaxIdle:     6,
		IdleTimeout: 240 * time.Second,
		Dial: func() (redis.Conn, error) {
			opts := []redis.DialOption{
				redis.DialConnectTimeout(5 * time.Second),
				redis.DialReadTimeout(2 * time.Second),
				redis.DialWriteTimeout(2 * time.Second),
				redis.DialDatabase(db),
				redis.DialPassword(pwd),
			}
			c, err := redis.Dial("tcp", addr, opts...)
			if err != nil {
				fmt.Printf("connect %s error %s", addr, err.Error())
				return nil, err
			}
			return c, err
		},
		TestOnBorrow: func(c redis.Conn, t time.Time) error {
			_, err := c.Do("PING")
			return err
		},
	}
}
func init() {
	maxIdle := MaxIdle
	//if v, ok := conf["MaxIdle"]; ok {
	//	maxIdle = int(v.(int64))
	//}
	maxActive := MaxActive
	//if v, ok := conf["MaxActive"]; ok {
	//	maxActive = int(v.(int64))
	//}

	// 建立连接池
	RedisClient = &redis.Pool{
		MaxIdle:     maxIdle,
		MaxActive:   maxActive,
		//IdleTimeout: MaxIdleTimeout * time.Second,
		IdleTimeout: MaxIdleTimeout ,
		Wait:        true,
		Dial: func() (redis.Conn, error) {
			con, err := redis.Dial("tcp",
				//conf["Host"].(string),
				"127.0.0.1:6379",
				redis.DialPassword(""),
				redis.DialDatabase(0),
				redis.DialConnectTimeout(timeout*time.Second),
				redis.DialReadTimeout(timeout*time.Second),
				redis.DialWriteTimeout(timeout*time.Second))
			if err != nil {
				return nil, err
			}
			return con, nil
		},
	}

	fmt.Println(RedisClient)
}
